import React, {Component,} from 'react';
import {Platform, AsyncStorage} from 'react-native';
import {connect} from 'react-redux';
import * as versionActions from '../../actions/versionActions';
import RootView from './RootView';
import SafeAreaViewPlus from '../../components/SafeAreaViewPlus';
import * as constant from "../../constant";
import * as navigationActions from "../../actions/navigationActions";
import {NavigationActions} from "react-navigation";

class RootController extends Component {

	static navigationOptions = () => {
		return {
			header: null
		};
	}

	async componentDidMount() {
		let logicVersion = await AsyncStorage.getItem('logicVersion');
		if (!logicVersion) {
			logicVersion = 1
			AsyncStorage.setItem('logicVersion', logicVersion.toString());
		}
		let clientType = Platform.OS === 'android' ? 1 : 0;
		this.props.checkUpdate(logicVersion, clientType, this.updateCallBack, this.noUpdateCallBack);
	}

	updateCallBack = async () => {

	}

	noUpdateCallBack = async () => {
		let userInfo = await AsyncStorage.getItem('userInfo');
		let routeName = !!userInfo ? constant.navigation.NAVIGATOR_HOME : constant.navigation.NAVIGATOR_LOGIN;
		this.props.navigation.reset([NavigationActions.navigate({routeName})], 0)
	}


	render() {
		return <SafeAreaViewPlus><RootView {...this.props}/></SafeAreaViewPlus>
	}

}

const mapStateToProps = (state) => ({
	...state.versionReducer
})

function mapDispatchToProps(dispatch) {
	return {
		checkUpdate: (logicVersion, clientType, updateCallBack, noUpdateCallBack) => {
			dispatch(versionActions.checkUpdate(logicVersion, clientType, updateCallBack, noUpdateCallBack))
		},
	};
}

export default connect(
		mapStateToProps,
		mapDispatchToProps
)(RootController);



